package com.yzjs.wx.service;

import com.google.gson.Gson;

import com.yzjs.base.BestPayServiceImpl;
import com.yzjs.base.PayRequest;
import com.yzjs.base.PayResponse;
import com.yzjs.enumeration.BestPayPlatformEnum;
import com.yzjs.enumeration.BestPayTypeEnum;
import com.yzjs.enumeration.OrderStatusEnum;
import com.yzjs.enumeration.PayPlatformEnum;
import com.yzjs.wx.dao.PayInfoMapper;
import com.yzjs.wx.dao.TAppUserInfoMapper;
import com.yzjs.wx.entity.PayInfo;
import com.yzjs.wx.entity.TAppUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PayService {

    private static final Logger log = LoggerFactory.getLogger(PayService.class);


    private final static String QUEUE_PAY_NOTIFY = "payNotify";

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    @Autowired
    private TAppUserInfoMapper appUserInfoMapper ;



    public PayResponse create(String openId,String orderId , BigDecimal orderAmout , BestPayTypeEnum bestPayTypeEnum){
        //写入数据库
        PayInfo payInfo = new PayInfo(openId,Long.parseLong(orderId),
                PayPlatformEnum.getByBestPayTypeEnum(bestPayTypeEnum).getCode(),
                OrderStatusEnum.NOTPAY.name(),
                orderAmout);
        payInfoMapper.insertSelective(payInfo);

        PayRequest payRequest = new PayRequest();
        payRequest.setOrderName("湖北bsn主干网");
        payRequest.setOrderId(orderId);
        payRequest.setOrderAmount(orderAmout.doubleValue());
        payRequest.setPayTypeEnum(bestPayTypeEnum);

        PayResponse payResponse = bestPayService.pay(payRequest);
        log.info("[发起支付] response = {}",payResponse);

        return payResponse;
    }

    public String asyncNotify(String notifyData){
        //签名验证
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("[异步通知] payResponse = {}",payResponse);

        //金额校验
        PayInfo payInfo = payInfoMapper.selectByOrderNo(Long.parseLong(payResponse.getOrderId()));
        if(payInfo == null){
            throw new RuntimeException("通过orderNo查询到到结果为null");
        }
        if(!payInfo.getPlatformStatus().equals(OrderStatusEnum.SUCCESS.name())){
            if(payInfo.getPayAmount().compareTo(BigDecimal.valueOf(payResponse.getOrderAmount())) != 0 ){
                throw new RuntimeException("异步通知中到金额与数据库里到不一致，orderNo = " + payInfo.getOrderNo());
            }
            //修改订单支付状态
            payInfo.setPlatformStatus(OrderStatusEnum.SUCCESS.name());
            payInfo.setPlatformNumber(payResponse.getOutTradeNo());
            payInfo.setUpdateTime(null);
            payInfoMapper.updateByPrimaryKeySelective(payInfo);

            // 修改账户金额
            TAppUserInfo tAppUserInfo = appUserInfoMapper.selectByOpenId(payInfo.getUserId());
            if (tAppUserInfo == null) {
                throw new RuntimeException("充值账户不存在，openId( = " + payInfo.getUserId());
            }
            tAppUserInfo.setAccountAmount(tAppUserInfo.getAccountAmount().add(payInfo.getPayAmount()));
            appUserInfoMapper.updateByPrimaryKeySelective(tAppUserInfo);
        }

        //告诉平台不再通知
        if(payResponse.getPayPlatformEnum() == BestPayPlatformEnum.WX){
            return "<xml>\n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        }
        throw new RuntimeException("异步通知中错误的支付平台");
    }

    public PayInfo queryByOrderId(Long orderNo) {
        return payInfoMapper.selectByOrderNo(orderNo);
    }
}
